const express = require('express')
const router = express.Router()
//爬虫
const request = require('request')
const cheerio = require('cheerio')
const userInfo = require('../mongodb/userInfo.js')
const jdShop = require('../mongodb/shop.js')

//注册接口
router.post('/register', function(req, res){
    
    const { username, paw, email, headerImg} = req.body

    userInfo.find({username}, function(err, data){
        //不管成功与否 都是 null 所以判断data的长度
        //console.log(err)
        if(data.length > 0){
            res.json({
                "msg": "用户名已存在",
                "code": -1
            })
            return
        }
        userInfo.create({
            username,
            paw,
            email,
            headerImg
        },(err, data) =>{
            //保存成功
            res.json({
                "msg": "注册成功",
                "code": 1
            })
        })

    })
})

//登陆接口
router.get('/login', (req, res) =>{
    //此时只需要拿到 密码 和用户名
    //看能 返回 数据
    const { username, paw} = req.query

    userInfo.findOne({username}, (err, data) =>{

        if(!data){
            res.json({
                "msg": "用户名不存在",
                "code": -1
            })
            return
        }
        
        //存在才能拿
        const {username, paw, email, headerImg} = data
        const userData = { username, email, paw, headerImg}

        if(paw === req.query.paw){
            res.json({
                userData,
                "code": 1
            })
            return
        }

        res.json({
            "msg": "密码错误",
            "code": 0
        })

    })
})

//商品接口
router.get('/findShop', (req, res) =>{
    const {keyWord, page, limit} =  req.query
    const name = keyWord
    const limitNum = page*limit 

    console.log(name,limitNum)
    // {skip: 0,limit: 1},
    jdShop.find({name}, (err, data) =>{
        if(data.length === 0){
            res.json({
                msg: '商品找不到',
                code: -1
            })

            return
        }

        res.json({
            shop: data,
            code: -1
        })

    })

    

})


module.exports = router